package com.rookieci.lib;


import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;

/**
 * @ClassName: FileOperateUtil
 * @Description: 文件操作工具类
 */
public class FileOperateUtil {
    public final static int ROOT = 0;// 根目录
    public final static int TYPE_IMAGE = 1;// 图片
    public final static int TYPE_THUMBNAIL = 2;// 缩略图
    public final static int TYPE_VIDEO = 3;// 视频
    public final static int TYPE_TEXT = 4;// 文本
    public final static int TYPE_ERR = 5;// 错误日志
    public final static int TYPE_Cache = 6;// 缓存
    public final static int TYPE_NetRes = 7;// 网络资源
    public final static int TYPE_Sound = 8;// 声音
    public final static int TYPE_Tmp = 9;// 临时文件
    public final static int GlideCache = 10;//GlideCache

    public static FileOperateUtil fileOperateUtil;

    public static FileOperateUtil getInstance() {
        if (fileOperateUtil == null) {
            synchronized (FileOperateUtil.class) {
                if (fileOperateUtil == null) {
                    fileOperateUtil = new FileOperateUtil();
                }
            }
        }
        return fileOperateUtil;
    }

    private FileOperateUtil() {
    }

    /**
     * 仅限公共目录使用
     */
    public String getSDCard() {
        return Environment.getExternalStorageDirectory().getPath();
    }

    /**
     * 打开内部储存位置(data/data/包名)
     */
    public static String getPrivatePath(Context context) {
        return context.getFilesDir().getAbsolutePath();
    }

    /**
     * 这是SDCard中的缓存目录，系统中的用getCacheDir();
     * 获取专属缓存位置
     */
    public static String getCachePath(Context context) {
        File file = context.getExternalCacheDir();
        if (file == null)
            return null;
        else return file.getAbsolutePath();
    }

    /**
     * @return getSDCard() + File.separator + dirName;
     */
    public String getAppDir() {
        Context context = LibApp.getContext();
        return context.getExternalFilesDir(null).getPath();
    }

    /**
     * 获取文件夹路径
     *
     * @param type 文件夹类别
     */
    public String getFolderPath(int type) {
        // 本业务文件主目录
        StringBuilder pathBuilder = new StringBuilder();
        // 添加应用存储路径
        pathBuilder.append(getAppDir());
        pathBuilder.append(File.separator);
        boolean isDefault = false;
        // 添加当然文件类别的路径
        switch (type) {
            case TYPE_IMAGE:
                pathBuilder.append("Image");
                break;
            case TYPE_VIDEO:
                pathBuilder.append("Video");
                break;
            case TYPE_TEXT:
                pathBuilder.append("Text");
                break;
            case TYPE_ERR:
                pathBuilder.append("Err");
                break;
            case TYPE_Cache:
                pathBuilder.append("Cache");
                break;
            case TYPE_NetRes:
                pathBuilder.append("NetRes");
                break;
            case TYPE_Sound:
                pathBuilder.append("Sound");
                break;
            case TYPE_THUMBNAIL:
                pathBuilder.append("Thumbnail");
                break;
            case TYPE_Tmp:
                pathBuilder.append("Temp");
                break;
            case GlideCache:
                pathBuilder.append("GlideCache");
                break;
            default:
                isDefault = true;
                break;
        }
        if (!isDefault) pathBuilder.append(File.separator);
        String folderPath = pathBuilder.toString();
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        return folderPath;
    }

    /**
     * 默认删除569下的文件
     */
    public void deleteDirFile() {
        deleteDirFile(TYPE_ERR);
        deleteDirFile(TYPE_Cache);
        deleteDirFile(TYPE_Tmp);
        deleteDirFile(GlideCache);
    }

    /**
     * 删除文件夹下的所有文件
     */
    public void deleteDirFile(int type) {
        String folderPath = getFolderPath(type);
        File file = new File(folderPath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File file1 : files)
                file1.delete();
        }
    }

    public void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteFile(files[i]);
            }
        }
        file.delete();
    }

    public long getDataSize() {
        long total = getDataSize(5);
        total += getDataSize(6);
        total += getDataSize(9);
        total += getDataSize(10);
        return total;
    }

    public long getDataSize(int type) {
        long total = 0;
        String folderPath = getFolderPath(type);
        File file = new File(folderPath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File file1 : files)
                total += file1.length();
            //file1.delete();
        }
        return total;
    }

    /**
     * 向文本文件写入数据<br>
     * 文件不存在新建
     *
     * @return 保存成功或失败
     */
    public static boolean textWrite(String fileName, String msg) {
        try {
            FileOutputStream fos = new FileOutputStream(fileName);
            fos.write(msg.getBytes());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static String getFileNameOfUrl(String url) {
        String name;
        try {
            String[] split = url.split("/");
            name = split[split.length - 1];
            split = name.split("\\?");
            name = split[0];
            split = name.split("#");
            name = split[0];
        } catch (Exception e) {
            name = System.currentTimeMillis() + "";
            if (BuildConfig.DEBUG) e.printStackTrace();
        }
        if (BuildConfig.DEBUG) Log.v("-->fileName:", name);
        return name;
    }

    private static String[][] videoType = {
            {"mp4", "video/mp4"}
            , {"3gp", "video/3gp"}
            , {"aiv", "video/aiv"}
            , {"rmvb", "video/rmvb"}
            , {"vob", "video/vob"}
            , {"flv", "video/flv"}
            , {"mkv", "video/mkv"}
            , {"mov", "video/mov"}
            , {"mpg", "video/mpg"}
            , {"png", "video/mpg"}
            , {"png", "image/png"}
            , {"jpg", "image/jpeg"}
            , {"jpeg", "image/jpeg"}
            , {"gif", "image/gif"}
    };

    public static String[][] getVideoType() {
        return videoType.clone();
    }

    /**
     * 用于上传的时候，设置MediaType
     */
    public static String getFileType(File file) {
        String name = file.getName();
        for (int i = 0; i < videoType.length; i++) {
            String[] strings = videoType[i];
            if (name.endsWith(strings[0])) {
                return strings[1];
            }
        }
        return "*/*";
    }
}